package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    //根据用户名字，查询数据库，给用户设置角色以及权限，并返回给框架
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(userService);
        User user = userService.FindUserByName(username);
        if(user==null){
            //无此员工，登录失败
            return null;
        }

        List<GrantedAuthority> list = new ArrayList<>();
        //根据员工ID查询该员工拥有的角色角色，
        Set<Role> roles = userService.FindRoleById(user.getId());
        //遍利该集合，并封装到List集合中，
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //根据角色ID查询该角色下拥有的权限
            Set<Permission> permissions = userService.FindPremissionById(role.getId());
//            遍利该权限集合，封装到List集合中
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        System.out.println(list);
        //返回给框架，用于框架作对比
        org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return user1;
    }
}
